#
# templatefilters.py
#
# Code idea comes from 
# http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Copyright 2009- Jeremy Nelson, Tomichi Informatics LLC
#
from google.appengine.ext import webapp
from google.appengine.ext import db
import logging
register = webapp.template.create_template_register()

def create_boolean(prop_dict):
    yes_str = '<input type="radio" name="%s" id="%s" value="1"' %\
              (prop_dict['name'],
               prop_dict['id'])
    no_str = '<input type="radio" name="%s" id="%s" value="0"' %\
             (prop_dict['name'],
              prop_dict['id'])
    if prop_dict.has_key('value'):
        if prop_dict['value'] == True:
            yes_str += ' checked="checked"'
        else:
            no_str += ' checked="checked"'
    yes_str += '>Yes</input>'
    no_str += '>No</input>'
    output_str = "%s<br/>%s" % (yes_str,no_str)
    return output_str

def create_select(property):
    output_str = ''
    output_str += '''<select id="%s" name="%s">
                             <option value="NONE">None</option>''' %\
                          (property['id'],property['name'])
    for choice in property['choices']:
        output_str += '''<option value="%s"''' % choice['key']
        if property.has_key('value'):
#            logging.error("ERROR IN create_select value=%s choice=%s" %
#                          (property['value'],choice))
            if property['value'] == choice['key']:
                output_str += ' selected="selected"'
        output_str += '''>%s</option>''' % choice['label']
    return output_str



def create_entity_checkbox(prop_dict):
    output_str = ''
    if prop_dict.has_key('value'):
        prop_value = prop_dict['value']
        if type(prop_value) == list:
            for row in prop_value:
                output_str += '''<input type="checkbox" name="%s" checked="checked" value="%s">''' %\
                                  (prop_dict['name'],
                                   row)
                if type(row) == db.Key:
                    entity = db.get(row)
                    if entity:
                        output_str += pretty_entity(entity)
                else:
                    output_str += row
                output_str += "</input><br/>"
        else:
            output_str += '''<input type="checkbox" name="%s" checked="checked"''' %\
                          prop_dict['name']
            try:
                output_str += '''value="%s">%s</input>''' %\
                              (prop_value.key(),
                               pretty_entity(prop_value))
            except:
                output_str += '''value="%s">%s</input>''' %\
                              (str(prop_value),
                               str(prop_value))
    return output_str
  
def endeavor_subtree(endeavor,view_type):
    if view_type == 'standard':
        external_url = endeavor.manifestation.access_address.value
    elif view_type == 'proxy':
        if endeavor.manifestation.proxy_address:
            external_url = endeavor.manifestation.proxy_address.value
        else:
            external_url = endeavor.manifestation.access_address.value
    output_str = '''<ul>
                    <li class="closed">
                    <span about="/endeavor/%s">
                    <span class="folder" property="mods:titleInfo"><a onclick="add_use('%s')" href="%s" target="_top">%s</a>
                    <sup><a href="#" onclick="DisplayEndeavor('%s')">?</a></sup>
                    </span></span>''' %\
                    (endeavor.key(),
                     endeavor.key(),
                     external_url,
                     endeavor.title.display_form,
                     endeavor.key())
    output_str += '''<ul><li><span class="file"><div class="record_display">
                     <label class="dsply">Is purchased?</label><div class="dsply">'''
    if endeavor.manifestation.is_subscription:
        output_str += 'Yes'
    else:
        output_str += 'No'
    output_str += '''</span><br/><label class="dsply">Access link:</label>'''
    output_str += '''<div class="dsply" property="mods:url"><a onclick="add_use('%s')" href="%s" target="_top">%s</a></div>
                     <label class="dsply">Description:</label><div class="dsply" property="mods:note">%s</div></div></li>
                     </ul></li>
    </ul>''' % (endeavor.key(),
                external_url,
                external_url,
                endeavor.manifestation.get_notes()[0].value)
    #logging.error(output_str)
    return output_str


def switch_url(endeavor,view_type):
    """ Takes endeavor and depending on view_type, returns proxy url
     or standard url
    """
    if view_type == 'proxy':
        if endeavor.manifestation.proxy_address:
            return endeavor.manifestation.proxy_address.value
        else:
            return endeavor.manifestation.access_address.value
    else:
        return endeavor.manifestation.access_address.value
    
def sparse(endeavor_key):
    endeavor = db.get(endeavor_key)
    output = {'title':endeavor.title.display_form,
              'key':endeavor_key}
    return output

def pretty_entity(entity):
    if hasattr(entity,'display_form'):
        return getattr(entity,'display_form')
    if hasattr(entity,'display_label'):
        return getattr(entity,'display_label')
    if hasattr(entity,'value'):
        return getattr(entity,'value')
    else:
        return str(entity)


def property_filter(property_dict):
    output_str = '<td>'
    if property_dict.has_key('is_required'):
        output_str += '''<span class="is_required">*</span>'''
    output_str += '''<label>%s</label></td><td>''' % property_dict['label']
    if property_dict['type_of'] == 'text':
        if property_dict.has_key('choices'):
            output_str += create_select(property_dict)
        else:
            output_str += '''<input type="text" size="30" id="%s" name="%s"''' %\
                          (property_dict['id'],
                           property_dict['name'])
            if property_dict.has_key('value'):
                output_str += ' value="%s"' % property_dict['value']
            output_str += "/>"
    elif property_dict['type_of'] == 'select':
        if property_dict.has_key('choices'):
            output_str += create_select(property_dict)
        else:
            output_str += '''<br/><textarea id="%s" name="%s" rows="2" cols="30">''' %\
                          (property_dict['id'],
                           property_dict['name'])
            if property_dict.has_key('value'):
                prop_value = property_dict['value']
                if type(prop_value) == list:
                    for row in prop_value:
                        output_str += "%s\n" % row
                else:
                    output_str += prop_value
            output_str += "</textarea>"
    elif property_dict['type_of'] == 'lkup_entities':
        output_str += '''<a href="#" onclick="GetEntity('%s','%s_div');">Find %s</a>
                         <div id="%s_div">
                       ''' %\
                      (property_dict['name'],
                       property_dict['id'],
                       property_dict['label'],
                       property_dict['id'])
        output_str += "%s</div>" % create_entity_checkbox(property_dict)
    elif property_dict['type_of'] == 'lkup_entity':
        output_str += '''<a href="#" onclick="GetEntity('%s','%s_div');">Find %s</a>
                         <div id="%s_div">
                      ''' %\
                      (property_dict['name'],
                       property_dict['id'],
                       property_dict['label'],
                       property_dict['id'])
        output_str += "%s</div>" % create_entity_checkbox(property_dict)
    elif property_dict['type_of'] == 'textarea':
        output_str += '''<textarea id="%s" name="%s" rows="2" cols="30">
                      ''' % (property_dict['id'],
                             property_dict['name'])
        if property_dict.has_key('value'):
            prop_value = property_dict['value']
            if type(prop_value) == list:
                for row in prop_value:
                    output_str += "%s\n" % row
            else:
                output_str += prop_value
        output_str += '''</textarea>'''
    elif property_dict['type_of'] == 'boolean':
        output_str += create_boolean(property_dict)
    elif property_dict['type_of'] == 'date':
        output_str += '''<input type="text" id="%s" name="%s"''' %\
                      (property_dict['id'],property_dict['name'])
        if property_dict.has_key('value'):
            output_str += ' value="%s"' % property_dict['value']
        output_str += '''> (YYYY-MM-DD)'''
    else:
        output_str += '''<input type="text" id="%s" name="%s">''' %\
                      (property_dict['id'],property_dict['name'])
    output_str += "</td>"
    return output_str


register.filter(property_filter)
register.filter(endeavor_subtree)
register.filter(pretty_entity)
register.filter(sparse)
register.filter(switch_url)
